package com.jy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jy.reggie.common.CustomException;
import com.jy.reggie.dto.DishDto;
import com.jy.reggie.dto.SetmealDto;
import com.jy.reggie.entity.*;
import com.jy.reggie.mapper.SetmealMapper;
import com.jy.reggie.service.CategoryService;
import com.jy.reggie.service.SetmealDishService;
import com.jy.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;



    /*新增套餐，同时需要保存套餐和菜品的关联关系*/
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(dish->{dish.setSetmealId(setmealDto.getId());});
        setmealDishService.saveBatch(setmealDishes);


    }

    /*套餐分页查询*/
    @Override
    public Page<SetmealDto> pagePlus(int page, int pageSize, String name) {
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        //条件查询构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询：SELECT id,category_id,name,price,status,code,description,image,create_time,update_time,create_user,update_user,is_deleted FROM setmeal WHERE (name LIKE ?) ORDER BY update_time DESC LIMIT ?
        setmealService.page(pageInfo,queryWrapper);


        //Page对象拷贝
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        //给新对象的records赋值
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(list);

        return setmealDtoPage;
    }

    /*删除套餐及其关联数据*/
    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可用删陈
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);

        //如果不能删除，抛出一个业务异常
        if(count>0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }


        //如果可以删除，先删除套餐表中的数据--setmeal
        this.removeByIds(ids);


        //删除关系表中的数据--setmealDish
        LambdaQueryWrapper<SetmealDish> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper2);
    }

    /*套餐停售启售*/
    @Override
    public void stopSaleByIds(Integer status, List<Long> ids) {
        List<Setmeal> setmeals = setmealService.listByIds(ids);
        setmeals.forEach(setmeal -> {
            setmeal.setStatus(status);
        });
        setmealService.updateBatchById(setmeals);
    }


    /*套餐数据更新回显*/
    @Override
    public SetmealDto getUpdate(Long id) {
//        查询套餐基本信息，从setmeal表查询
        Setmeal setmeal = this.getById(id);

//        查询当前套餐对应的菜品，从Setmeal_dish表查询
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> dishes = setmealDishService.list(queryWrapper);

//      拷贝数据到setmealDto
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(dishes);
        return setmealDto;

    }

    /*更新套餐*/
    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
//        更新setmeal表基本信息
        this.updateById(setmealDto);

//        清理当前套餐菜品数据---setmeal_dish表的delete操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);

//        添加当前提交过来的套餐菜品---setmeal_dish表的insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
        });
        setmealDishService.saveBatch(setmealDishes);
    }
}
